package com.starmark.sys.org.atomic.service.impl;


import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.starmark.core.framework.base.AbstractUniqueBaseService;
import com.starmark.core.framework.support.typehandler.AES;
import com.starmark.core.framework.util.BeanMapper;
import com.starmark.sys.org.api.dto.OrgElementDto;
import com.starmark.sys.org.api.dto.OrgUserInfoDto;
import com.starmark.sys.org.api.service.IOrgUserApiService;
import com.starmark.sys.org.atomic.entity.SysOrgUser;
import com.starmark.sys.org.atomic.mapper.SysOrgUserMapper;
import com.starmark.sys.org.atomic.service.ISysOrgUserDeptRelService;
import com.starmark.sys.org.atomic.service.ISysOrgUserService;
import com.starmark.sys.org.atomic.vo.SysOrgUserPageQueryVo;
import com.starmark.sys.org.atomic.vo.SysOrgUserVo;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * SysUser服务实现类
 *
 * @author starmark
 * @version 2016-08-27 22:39:42
 */
@Service("sysOrgUserService")
public class SysOrgUserServiceImpl extends AbstractUniqueBaseService<SysOrgUserMapper, SysOrgUser> implements ISysOrgUserService,
        IOrgUserApiService {


    @Autowired
    private ISysOrgUserDeptRelService orgUserDeptRelService;

    @Override
    public SysOrgUser findUserByLoginName(String loginName) {
        return this.getBaseMapper().findUserByLoginName(loginName);
    }

    @Override
    public Page<SysOrgUser> selectUserPage(SysOrgUserPageQueryVo pageQueryVo) {
        Page<SysOrgUser> page = new Page<>(pageQueryVo.getCurrPage(), pageQueryVo.getLimit());

        IPage<SysOrgUser> pageResult = this.getBaseMapper().selectUserPage(page, pageQueryVo);
        page.setRecords(pageResult.getRecords());
        page.setTotal(pageResult.getTotal());
        return page;
    }


    @Override
    public void buildPageSearch(Map<String, Object> params, QueryWrapper<SysOrgUser> eWrapper) {
        if (params.get("keyword") != null && StrUtil.isNotEmpty(params.get("keyword") + "")) {
            eWrapper.like("name", params.get("keyword") + "");
        }

    }

    @Override
    @Cached(name = "sysOrgUserService:loadUserById:", key = "#id", cacheType = CacheType.BOTH)
    public OrgUserInfoDto loadUserById(String id) {
        return BeanMapper.map(this.getById(id), OrgUserInfoDto.class);
    }

    @Override
    public OrgUserInfoDto loadUserInfoByMap(Map<String, Object> userMap) {
        List<SysOrgUser> orgUsers = this.baseMapper.selectByMap(userMap);
        if (orgUsers.size() != 1) {
            throw new RuntimeException("查找出来的用户不是唯一" + userMap);
        }
        return BeanMapper.map(orgUsers.get(0), OrgUserInfoDto.class);
    }

    @Override
    public List<OrgElementDto> getOrgTreeBySearchkey(String searchKey, int pageSize) {
        return this.getBaseMapper().getOrgTreeBySearchkey(searchKey, pageSize);
    }


    @Override
    public List<OrgElementDto> getOrgTreeById(String id) {
        return this.getBaseMapper().getOrgTreeById(id);
    }

    @Override
    public List<OrgUserInfoDto> getUserListByIds(List<String> userIds) {
        Collection<SysOrgUser> userList = this.listByIds(userIds);
        return BeanMapper.mapList(userList, OrgUserInfoDto.class);
    }


    @Override
    public boolean checkUserPassword(String userId, String password) {

        return this.getBaseMapper().checkUserPassword(userId, AES.encrypt(password));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveUserInfo(SysOrgUserVo sysOrgUserVo) {
        SysOrgUser sysOrgUser = BeanMapper.map(sysOrgUserVo, SysOrgUser.class);
        this.save(sysOrgUser);
        //更新用户部门关系
        orgUserDeptRelService.saveUserDeptRel(sysOrgUser.getId(), sysOrgUserVo.getUserDeptRel());
        return sysOrgUser.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateUserInfo(SysOrgUserVo sysOrgUserVo) {
        SysOrgUser sysOrgUser = BeanMapper.map(sysOrgUserVo, SysOrgUser.class);
        //不更新密码
        sysOrgUser.setPassword(null);
        this.updateById(sysOrgUser);
        //更新用户部门关系
        orgUserDeptRelService.saveUserDeptRel(sysOrgUser.getId(), sysOrgUserVo.getUserDeptRel());
        return sysOrgUser.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePwd(String userId, String password) {
        Assert.hasText(userId, "用户ID不允许为空");
        SysOrgUser user = this.getById(userId);
        Assert.notNull(user, "用户不存在:" + userId);
        this.getBaseMapper().updatePwd(userId, AES.encrypt(password));
    }


    @Override
    public String getDbFieldCode() {
        return "login_name";
    }
}
